package com.lzzy.service.impl;

import com.lzzy.dao.ArticleRepository;
import com.lzzy.model.domain.Article;
import com.lzzy.service.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ArticleServicelmpl implements IArticleService {

    //持久层
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    //查询所有文章
    @Override
    public List<Article> findarticleall(){
        return articleRepository.findByIdNotNull();
    }

    //分页展示
    @Override
    public Page<Article> pageArticle(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return articleRepository.findAll(pageable);
    }



    @Override
    public Article findArticleById(Integer id){
        Object object = redisTemplate.opsForValue().get("article"+id);
        if (object != null) {
            return (Article)object;
        }
        else{
            Optional<Article> article= articleRepository.findById(id);
            if (article.isPresent()) {
                redisTemplate.opsForValue().set("article"+id, article.get());
                return article.get();
            }
            else {
                return null;
            }
        }
    }

    //新增文章
    @Override
    public Article addArticle(String title, String category, String content){
        Article article = new Article();
        //添加标题
        article.setTitle(title);
        //添加分类标签
        article.setCategories(category);
        //添加文章内容
        article.setContent(content);
        //添加时间
        article.setCreated(new Date());
        return articleRepository.save(article);
    }

  //删除文章
    public void deleteById(Integer id){
       articleRepository.deleteArticle(id);
        redisTemplate.delete("article"+id);
    }

    //修改文章
    public void updateArticle(String title,String content,String categories,Integer id){
        articleRepository.updateArticle(title,content,categories,id);
        Article article = findArticleById(id);
        article.setTitle(title);
        article.setCategories(categories);
        article.setContent(content);
        articleRepository.save(article);
        redisTemplate.opsForValue().set("article"+id, article);
    }
}
